/**
 * Author: Todd Kerpelman
 * Date: 6/15/12
 * Time: 5:11 PM
 *
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package net.kerp.hangoutSpace {
import flash.display.BitmapData;
import flash.geom.Point;
import flash.geom.Rectangle;

public class ScrollingBitmap {
  private var _origBitmapData:BitmapData;
  private var _scrollFactor:Number;
  private var _targetBitmapData:BitmapData;
  private var _offset:Point;
  private var _width:int;
  private var _height:int;

  public function ScrollingBitmap(origBitmapData:BitmapData, targetBitmapData:BitmapData) {
    _origBitmapData = origBitmapData;
    _width = _origBitmapData.width;
    _height = _origBitmapData.height;
    _targetBitmapData = targetBitmapData;
    _scrollFactor = 1.0;
    _offset = new Point(0,0);

  }

  public function get scrollFactor():Number {
    return _scrollFactor;
  }

  public function set scrollFactor(value:Number):void {
    _scrollFactor = value;
  }

  public function scrollTarget(amtX:Number, amtY:Number):void {
    _offset.x += amtX * _scrollFactor;
    _offset.y += amtY * _scrollFactor;
    if (_offset.x < 0) {_offset.x += _width;}
    if (_offset.x > _width) {_offset.x -=  _width;}
    if (_offset.y < 0) {_offset.y += _height;}
    if (_offset.y > _height) {_offset.y -=  _height;}
    copyScrollingBitmap();
  }

  // TODO: Should I do this with integer values instead?
  private function copyScrollingBitmap():void {
    var leftoverx:Number = _width - _offset.x;
    var leftovery:Number = _height - _offset.y;

    // Upper left to bottom right
    _targetBitmapData.copyPixels(_origBitmapData,new Rectangle(0,0,_offset.x,_offset.y), new Point(leftoverx, leftovery));
    // Bottom right to upper left
    _targetBitmapData.copyPixels(_origBitmapData,new Rectangle(_offset.x, _offset.y, leftoverx, leftovery), new Point(0,0));
    // Bottom left to upper right
    _targetBitmapData.copyPixels(_origBitmapData,new Rectangle(0, _offset.y, _offset.x, leftovery), new Point(leftoverx,0));
    // Upper right to bottom left
    _targetBitmapData.copyPixels(_origBitmapData,new Rectangle(_offset.x, 0, leftoverx, _offset.y), new Point(0,leftovery));

  }

  
}
}
